package web.banco;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import web.banco.entity.Approval;


public class TesteDatabase extends HttpServlet {

	private static final long serialVersionUID = 1L;

	private static EntityManagerFactory emf;
    private static EntityManager em;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
    		throws ServletException, IOException {

        // Create EntityManagerFactory for persistent unit named "pu1"
        // to be used in this test
        emf = Persistence.createEntityManagerFactory("pu1");

        // Persist all entities
        createTransactionalEntityManager();
        System.out.println("Inserting Approvals... " + testInsert());
        closeTransactionalEntityManager();

        // Test update
        createTransactionalEntityManager();
        System.out.println("Updating Approvals... " + testUpdate());
        closeTransactionalEntityManager();

        // Test query and navigation
        createEntityManager();
        System.out.println("Verifying that all are inserted... " + verifyInsert());
        closeEntityManager();

        // Get a detached instance in a new EntityManager
        createEntityManager();
        Approval c = findApproval("Joe Smith");
        closeEntityManager();

        // Remove all entities
        createTransactionalEntityManager();
        System.out.println("Removing all... " + testDelete(c));
        closeTransactionalEntityManager();

        // Query the results
        createEntityManager();
        System.out.println("Verifying that all are removed... " + verifyDelete());
        closeEntityManager();

        resp.setContentType("text/plain");
		PrintWriter writer = resp.getWriter();
		writer.println("<html><body>OK!</body></html>");
		writer.close();
        
    }
    public static void main(String[] args) {

        // Create EntityManagerFactory for persistent unit named "pu1"
        // to be used in this test
        emf = Persistence.createEntityManagerFactory("pu1");

        // Persist all entities
        createTransactionalEntityManager();
        System.out.println("Inserting Approvals... " + testInsert());
        closeTransactionalEntityManager();

        // Test update
        createTransactionalEntityManager();
        System.out.println("Updating Approvals... " + testUpdate());
        closeTransactionalEntityManager();

        // Test query and navigation
        createEntityManager();
        System.out.println("Verifying that all are inserted... " + verifyInsert());
        closeEntityManager();

        // Get a detached instance in a new EntityManager
        createEntityManager();
        Approval c = findApproval("Joe Smith");
        closeEntityManager();

        // Remove all entities
        createTransactionalEntityManager();
        System.out.println("Removing all... " + testDelete(c));
        closeTransactionalEntityManager();

        // Query the results
        createEntityManager();
        System.out.println("Verifying that all are removed... " + verifyDelete());
        closeEntityManager();

    }

    private static String testInsert() {

        // Create new customer
    	Approval customer0 = new Approval();
        //customer0.setId(1);
        customer0.setClient("Joe Smith");
        customer0.setSecurityKey("Joe Smith");
        customer0.setStatus("Joe Smith");

        // Persist the customer
        em.persist(customer0);
        em.flush();

        System.out.println("Generated ID = "+customer0.getId());
        
        return "OK";
    }
        
    private static String verifyInsert() {

    	Approval c = findApproval("Joe Smith");

        if (c == null) {
            throw new RuntimeException("Joe Smith not found");
        }

        System.out.println("Generated ID = "+c.getId());
        
        return "OK";
    }

    private static String testUpdate() { 

    	Approval c = findApproval("Joe Smith");

        if (c == null) {
            throw new RuntimeException("Joe Smith not found");
        }

        System.out.println("status antes = "+c.getStatus());
        c.setStatus("newstatus");
        em.merge(c);
        em.flush();
        System.out.println("status depois = "+c.getStatus());
        
        System.out.println("Generated ID = "+c.getId());
        
        return "OK";
    }

    private static String testDelete(Approval c) {

        // Merge the customer to the new persistence context
    	Approval c0 = em.merge(c);

        // Delete all records.
        em.remove(c0);

        return "OK";
    }

    private static String verifyDelete() {

        Query q = em.createQuery("select c from Approval c");
        List results = q.getResultList();

        if (results == null || results.size() != 0) {
            throw new RuntimeException("Unexpected number of customers after delete");
        }

        return "OK";
    }

    private static Approval findApproval(String client) {

        Query q = em.createQuery("select a from Approval a where a.client = :client");
        q.setParameter("client", client);
        return (Approval)q.getSingleResult();

    }

    private static void createTransactionalEntityManager() {

        // Create a new EntityManager
        em = emf.createEntityManager();

        // Begin transaction
        em.getTransaction().begin();
    }

    private static void closeTransactionalEntityManager() {

        // Commit the transaction
        em.getTransaction().commit();

        // Close this EntityManager
        em.close();
    }

    private static void createEntityManager() {

        // Create a new EntityManager
        em = emf.createEntityManager();
    }

    private static void closeEntityManager() {

        // Close this EntityManager
        em.close();
    }

}
